<?php

namespace decrypt;
class Curl3Des{

	var $deviceid = '';
	var $user = '';
	var $lsh = '';
	var $cipherText = '';
	var $HcipherText = '';
	var $decrypted_data ='';

	//加密
	function encrypt($str,$key)
	{
		$size = mcrypt_get_block_size(MCRYPT_3DES,'ecb');
		$str = $this->pkcs5_pad($str, $size);
		//$td = mcrypt_module_open(MCRYPT_3DES, '', 'ecb', '');
		//$iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);

		$cipher = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');
		$iv     = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_3DES,MCRYPT_MODE_ECB), MCRYPT_RAND);
		if (mcrypt_generic_init($cipher, substr($key,0,24), $iv) != -1)
		{
			$this->cipherText = mcrypt_generic($cipher,$str);
			mcrypt_generic_deinit($cipher);
		}
		mcrypt_module_close($cipher);

		return  base64_encode($this->cipherText);
	}

	//解密
	function decrypt($str,$key)
	{
		$str = base64_decode($str);
		$cipher = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');
		$iv     = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_3DES,MCRYPT_MODE_ECB), MCRYPT_RAND);
		if (mcrypt_generic_init($cipher, substr($key,0,24), $iv) != -1)
		{
			$this->decrypted_data = mdecrypt_generic($cipher,$str);
			mcrypt_generic_deinit($cipher);
		}
		mcrypt_module_close($cipher);
		
		return $this->pkcs5_unpad($this->decrypted_data);
	}

	private function pad ($data)
	{
		$data = str_replace("\n","",$data);
		$data = str_replace("\t","",$data);
		$data = str_replace("\r","",$data);
		return $data;
	}

	private function unpading ($text)
	{
		$pad = ord($text{strlen($text) - 1});
		if ($pad > strlen($text)) {
			return false;
		}
		if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
			return false;
		}
		return substr($text, 0, - 1 * $pad);
	}

	//填充密码，填充至8的倍数
	private function padding( $str )
	{
		$len = 8 - strlen( $str ) % 8;
		for ( $i = 0; $i < $len; $i++ )
		{
			$str .= 0;
		}
		return $str ;
	}

	private function unpadding($str){

	}

	function pkcs5_pad ($text, $blocksize) {
		$pad = $blocksize - (strlen($text) % $blocksize);
		//echo $pad;echo "</br>";
		return $text . str_repeat(chr($pad), $pad);
	}
	function pkcs5_unpad($text) {
		$pad = ord($text{strlen($text)-1});
		if ($pad > strlen($text)) return false;
		if (strspn($text, chr($pad), strlen($text) - $pad) != $pad)return false;
		return substr($text, 0, -1 * $pad);
	}
}
